package com.addzero.web.ui.hooks.tree

import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight
import androidx.compose.material.icons.filled.KeyboardArrowDown
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.unit.dp


/**
 * 树形导航组件
 * 用于渲染树形结构的导航菜单，支持展开/折叠、选中状态等功能
 */
@Composable
fun <T> TreeNavigation(
    nodes: List<TreeNode<T>>,
    currentSelectedId: String = "",
    initialExpandedIds: Set<String> = emptySet(),
    onNodeSelected: (String) -> Unit,
    getNodeIcon: ((TreeNode<T>) -> ImageVector?)? = null,
    customNodeContent: (@Composable (TreeNode<T>, Boolean, Boolean) -> Unit)? = null
) {
    // 记录展开的节点ID
    val expandedNodeIds = remember { mutableStateOf(initialExpandedIds) }

    // 内部使用的切换展开状态的函数
    val onToggleExpand: (String) -> Unit = { nodeId ->
        expandedNodeIds.value = if (expandedNodeIds.value.contains(nodeId)) {
            expandedNodeIds.value - nodeId
        } else {
            expandedNodeIds.value + nodeId
        }
    }

    // 渲染树形结构
    Column {
        nodes.forEach { node ->
            TreeNavigationNode(
                node = node,
                level = 0,
                isExpanded = expandedNodeIds.value.contains(node.id),
                isSelected = currentSelectedId == node.id,
                onNodeSelected = onNodeSelected,
                onToggleExpand = onToggleExpand, // 传递内部的切换函数
                getNodeIcon = getNodeIcon,
                customNodeContent = customNodeContent,
                expandedNodeIds = expandedNodeIds.value,
                currentSelectedId = currentSelectedId
            )
        }
    }
}

/**
 * 树形导航节点组件
 * 递归渲染树形节点及其子节点
 */
@Composable
private fun <T> TreeNavigationNode(
    node: TreeNode<T>,
    level: Int, // level 由 TreeSider 计算并传入 TreeNode
    isExpanded: Boolean,
    isSelected: Boolean,
    onNodeSelected: (String) -> Unit,
    onToggleExpand: (String) -> Unit, // 接收切换函数
    getNodeIcon: ((TreeNode<T>) -> ImageVector?)? = null,
    customNodeContent: (@Composable (TreeNode<T>, Boolean, Boolean) -> Unit)? = null,
    expandedNodeIds: Set<String>,
    currentSelectedId: String
) {
    Column {
        // 包裹整个节点内容，并添加统一的点击处理
        Box(
            modifier = Modifier.clickable { 
                // 统一处理点击：选择 + 可能的展开/折叠
                onNodeSelected(node.id) 
                if (node.children.isNotEmpty()) {
                    onToggleExpand(node.id)
                }
            }
        ) {
            // 根据是否有自定义内容，渲染节点
            if (customNodeContent != null) {
                // 调用自定义渲染，它不需要处理点击
                customNodeContent(node, isSelected, isExpanded)
            } else {
                // 使用默认渲染 (移除内部的 onClick)
                NavigationDrawerItem(
                    icon = {
                        getNodeIcon?.invoke(node)?.let { icon ->
                            Icon(icon, contentDescription = node.label)
                        }
                    },
                    label = { Text(node.label) },
                    badge = {
                        if (node.children.isNotEmpty()) {
                            val arrowIcon = if (isExpanded) {
                                Icons.Default.KeyboardArrowDown
                            } else {
                                Icons.AutoMirrored.Filled.KeyboardArrowRight
                            }
                            Icon(
                                imageVector = arrowIcon,
                                contentDescription = if (isExpanded) "折叠" else "展开",
                                modifier = Modifier.size(24.dp)
                            )
                        }
                    },
                    selected = isSelected,
                    onClick = { /* 由外部 Box 的 clickable 处理 */ }, // 内部 onClick 留空
                    modifier = Modifier.padding(
                        start = (node.level * 16).dp, // 使用 TreeNode 中的 level 计算缩进
                        top = 4.dp,
                        end = 8.dp,
                        bottom = 4.dp
                    ),
                    colors = NavigationDrawerItemDefaults.colors(
                        selectedContainerColor = MaterialTheme.colorScheme.primary.copy(alpha = 0.2f),
                        unselectedContainerColor = MaterialTheme.colorScheme.surface
                    )
                )
            }
        }

        // 如果节点展开且有子节点，则递归渲染子节点
        if (isExpanded && node.children.isNotEmpty()) {
            node.children.forEach { childNode ->
                TreeNavigationNode(
                    node = childNode,
                    level = childNode.level, // 使用子节点的 level
                    isExpanded = expandedNodeIds.contains(childNode.id),
                    isSelected = currentSelectedId == childNode.id,
                    onNodeSelected = onNodeSelected,
                    onToggleExpand = onToggleExpand,
                    getNodeIcon = getNodeIcon,
                    customNodeContent = customNodeContent,
                    expandedNodeIds = expandedNodeIds,
                    currentSelectedId = currentSelectedId
                )
            }
        }
    }
}
